package com.ygou.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.ygou.pojo.Log;

public class AppendContentToFile {
	/**
	 * 打印日志
	 * @param userId 当前管理员ID
	 * @param Action 自己写一句操作的内容
	 */
	@SuppressWarnings("static-access")
	public static void fileLogPrint(String userId,String Action){
		Date d=new Date();
		String fileName=Tools.getNow()+".txt";
			String filePath="E:\\"+fileName;
			File file=new File(filePath);
			if (!file.exists()) {
				file.getParentFile().mkdir();
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			BufferedWriter out = null;
			try {
			out = new BufferedWriter(new OutputStreamWriter(
			new FileOutputStream(filePath, true),"UTF-8"));
			out.write(userId+"##"+Action+"##"+d+"\r\n");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			try {
				if(out!=null){
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			}
			
	}
	public static List<Log> read(String fileName){
		List<Log> loggers=new ArrayList<Log>();
		try { // 防止文件建立或读取失败，用catch捕捉错误并打印，也可以throw  

            /* 读入TXT文件 */  
            String pathname = "E:\\"+fileName; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径  
            File filename = new File(pathname); // 要读取以上路径的input。txt文件  
            if(!filename.exists()){
            	try {
            		filename.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            InputStreamReader reader = new InputStreamReader(  
                    new FileInputStream(filename),"UTF-8"); // 建立一个输入流对象reader  
            BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言  
            String line = "";  
            	while (line != null) {  
                    line = br.readLine(); // 一次读入一行数据 
                  List<String> logs=Arrays.asList(line.split("##"));
                  Log g=new Log();
                  g.setId(Integer.parseInt(logs.get(0)));
                  g.setAction(logs.get(1));
                  g.setDate(new Date(logs.get(2)));
                  loggers.add(g);
                } 
		}catch(Exception e){
			new  Throwable("文件不存在");
		}
		return loggers;
	}
}
